'use strict';
const createConfig = require('uni-config-center')
const uniPay = require('uni-pay')
let uniID = require('uni-id')
const db = uniCloud.database()

exports.main = async (event, context) => {
  uniID = uniID.createInstance({
    context
  })
  const uniPayConfig = createConfig({
    pluginId: 'uni-pay'
  })
  const {
    wxConfigMp,
    wxConfigApp,
    wxConfigH5,
    aliConfigMp,
    aliConfigApp,
    aliConfigH5,
	appleConfigApp,
    // aliConfigSandbox
  } = uniPayConfig.requireFile('config.js')
  const {
    outTradeNo,
	lx,
    uniIdToken
  } = event
  
  let url = '';
  let updateurl = '';
  if(lx==1){
	  url = 'http://www.txzh.com.cn/api.php?act=orderinfo';
	  updateurl = 'http://www.txzh.com.cn/api.php?act=updateorder';
  }
  
  if(lx==2){
  	  url = 'http://www.txzh.com.cn/api.php?act=rechargeinfo';
	  updateurl = 'http://www.txzh.com.cn/api.php?act=updaterecharge';
  }
	const orderList = await uniCloud.httpclient.request(url, {
	    method: 'GET',
	    data: {
	      ordersn: outTradeNo
	    },
	    contentType: 'json', // 指定以application/json发送data内的数据
	    dataType: 'json' // 指定返回值为json格式，自动进行parse
	  })
  
  if (orderList.data.paystatus===1) {
  	return {
  	  orderPaid: true
  	}
  }
 
 
  
const provider = orderList.data.provider;
 
  let uniPayInstance
  switch (provider + '_' + context.PLATFORM) {
    case 'wxpay_mp-weixin':
      uniPayInstance = uniPay.initWeixin(wxConfigMp)
      break;
    case 'wxpay_app-plus':
      uniPayInstance = uniPay.initWeixin(wxConfigApp)
      break;
    case 'wxpay_h5':
      uniPayInstance = uniPay.initWeixin(wxConfigH5)
      break;
    case 'alipay_mp-alipay':
      uniPayInstance = uniPay.initAlipay(aliConfigMp)
      break;
    case 'alipay_app-plus':
      uniPayInstance = uniPay.initAlipay(aliConfigApp)
      break;
    case 'alipay_h5':
      uniPayInstance = uniPay.initAlipay(aliConfigH5)
      // uniPayInstance = uniPay.initAlipay(aliConfigSandbox)
      break;
	case 'appleiap-plus':
	  uniPayInstance = uniPay.initappleiapPayment(appleConfigApp)
	  break;
    default:
      return {
        code: -1,
          msg: '参数错误'
      }
  }

  let queryResult = await uniPayInstance.orderQuery({
    outTradeNo
  })
  
  if (queryResult.tradeState === 'SUCCESS' || queryResult.tradeState === 'FINISHED') {
    
	const ret = await uniCloud.httpclient.request(updateurl, {
	    method: 'GET',
	    data: {
	      ordersn: queryResult.outTradeNo,
		  transactionId:queryResult.transactionId,
		  totalFee:queryResult.totalFee
	    },
	    contentType: 'json', // 指定以application/json发送data内的数据
	    dataType: 'json' // 指定返回值为json格式，自动进行parse
	  })
	 
    return {
      orderPaid: true
    }
  }
  return {
    orderPaid: false
  }
};
